import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  FlatList,
  Image,
  TouchableOpacity,
  View,
  ActivityIndicator,
  Alert,
} from "react-native";
import { useRouter, useFocusEffect } from "expo-router";
import { useCallback } from "react";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";
import { AI_ASSISTANT } from "@/constants/AIAssistant";
import { chatAPI } from "@/services/chatAPI";
import { useAuth } from "@/contexts/AuthContext";

export default function ChatScreen() {
  const colorScheme = useColorScheme();
  const router = useRouter();
  const tintColor = Colors[colorScheme ?? "light"].tint;
  const { userToken } = useAuth();

  const [chatData, setChatData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  // 加载聊天列表
  const loadChatList = async () => {
    try {
      setIsLoading(true);
      const response = await chatAPI.getConversations();
      if (response.data) {
        setChatData(response.data);
      }
    } catch (error) {
      console.error("获取聊天列表失败:", error);
      Alert.alert("错误", "获取聊天列表失败，请稍后再试");
      // 如果API调用失败，使用模拟数据
      setChatData([
        {
          id: "1",
          name: "张阿姨",
          avatar: { uri: "https://randomuser.me/api/portraits/women/65.jpg" },
          lastMessage: "今天天气真好，要不要一起去公园散步？",
          time: "10:30",
          unread: 2,
        },
        {
          id: "2",
          name: "李大爷",
          avatar: { uri: "https://randomuser.me/api/portraits/men/72.jpg" },
          lastMessage: "我找到了一个很好的太极拳教程，分享给你",
          time: "昨天",
          unread: 0,
        },
        {
          id: "3",
          name: "王奶奶",
          avatar: { uri: "https://randomuser.me/api/portraits/women/70.jpg" },
          lastMessage: "孙子的照片，你看看多可爱",
          time: "昨天",
          unread: 1,
        },
        {
          id: "4",
          name: "赵叔叔",
          avatar: { uri: "https://randomuser.me/api/portraits/men/67.jpg" },
          lastMessage: "下棋吗？我最近学了几个新招式",
          time: "周二",
          unread: 0,
        },
        {
          id: "5",
          name: "刘大妈",
          avatar: { uri: "https://randomuser.me/api/portraits/women/68.jpg" },
          lastMessage: "我做了些点心，明天带给你尝尝",
          time: "周一",
          unread: 0,
        },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  // 初始加载聊天列表
  useEffect(() => {
    if (userToken) {
      loadChatList();
    } else {
      setIsLoading(false);
    }
  }, [userToken]);

  // 当页面重新获得焦点时刷新聊天列表
  useFocusEffect(
    useCallback(() => {
      if (userToken) {
        loadChatList();
      }
      return () => {};
    }, [userToken])
  );

  const renderChatItem = ({ item }) => (
    <TouchableOpacity
      style={styles.chatItem}
      onPress={() => {
        // 导航到聊天详情页面
        router.push(`/chat/${item.id}`);
      }}
    >
      <View style={styles.avatarContainer}>
        <Image source={item.avatar} style={styles.avatar} />
        {item.unread > 0 && (
          <View style={styles.unreadBadge}>
            <ThemedText style={styles.unreadText}>{item.unread}</ThemedText>
          </View>
        )}
      </View>
      <View style={styles.chatContent}>
        <View style={styles.chatHeader}>
          <ThemedText style={styles.nameText}>{item.name}</ThemedText>
          <ThemedText style={styles.timeText}>{item.time}</ThemedText>
        </View>
        <ThemedText
          style={styles.messageText}
          numberOfLines={1}
          ellipsizeMode='tail'
        >
          {item.lastMessage}
        </ThemedText>
      </View>
    </TouchableOpacity>
  );

  // AI助手聊天项
  const renderAIAssistant = () => (
    <TouchableOpacity
      style={[styles.chatItem, styles.aiAssistantItem]}
      onPress={() => {
        router.push(`/chat/ai-assistant`);
      }}
    >
      <View style={styles.avatarContainer}>
        <Image source={AI_ASSISTANT.avatar} style={styles.avatar} />
        <View style={styles.onlineBadge} />
      </View>
      <View style={styles.chatContent}>
        <View style={styles.chatHeader}>
          <ThemedText style={styles.nameText}>{AI_ASSISTANT.name}</ThemedText>
          <ThemedText style={styles.timeText}>在线</ThemedText>
        </View>
        <ThemedText
          style={styles.messageText}
          numberOfLines={1}
          ellipsizeMode='tail'
        >
          {AI_ASSISTANT.description}
        </ThemedText>
      </View>
    </TouchableOpacity>
  );

  // 渲染加载指示器
  const renderLoading = () => {
    if (!isLoading) return null;

    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size='large' color={tintColor} />
        <ThemedText style={styles.loadingText}>加载聊天列表...</ThemedText>
      </View>
    );
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <ThemedText style={styles.headerTitle}>聊天</ThemedText>
      </View>

      {isLoading ? (
        renderLoading()
      ) : (
        <FlatList
          data={chatData}
          renderItem={renderChatItem}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.listContent}
          ListHeaderComponent={renderAIAssistant}
        />
      )}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  headerTitle: {
    fontSize: 28,
    fontWeight: "bold",
  },
  listContent: {
    paddingVertical: 10,
  },
  chatItem: {
    flexDirection: "row",
    padding: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  aiAssistantItem: {
    backgroundColor: "rgba(10, 126, 164, 0.05)",
    borderLeftWidth: 3,
    borderLeftColor: "#0a7ea4",
  },
  avatarContainer: {
    position: "relative",
    marginRight: 15,
  },
  avatar: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: "#F0F0F0", // 添加背景色，防止头像加载前的空白
  },
  unreadBadge: {
    position: "absolute",
    top: 0,
    right: 0,
    backgroundColor: "#FF6B6B",
    width: 20,
    height: 20,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  onlineBadge: {
    position: "absolute",
    bottom: 0,
    right: 0,
    backgroundColor: "#4CAF50",
    width: 15,
    height: 15,
    borderRadius: 8,
    borderWidth: 2,
    borderColor: "#fff",
  },
  unreadText: {
    color: "#fff",
    fontSize: 12,
    fontWeight: "bold",
  },
  chatContent: {
    flex: 1,
    justifyContent: "center",
  },
  chatHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    marginBottom: 5,
  },
  nameText: {
    fontSize: 18,
    fontWeight: "bold",
  },
  timeText: {
    fontSize: 14,
    color: "#999",
  },
  messageText: {
    fontSize: 16,
    color: "#666",
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: "#666",
  },
});
